/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package metier;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;

/**
 *
 * @author laurent
 */
//TODO : Rajouter le traitement des identifiants des index
public class GestionDocuments {

    private static GestionDocuments instance = null;
    private Map<Integer, String> index;
    private String path;
    private int currentId;
    private FopFactory fopFactory;

    public GestionDocuments() {
        this.path = "./Documents/";
        File idx = new File(path + "index.xml");
        if (idx.exists()) {
            GestionXml xml = new GestionXml();
            try {
                this.index = xml.deserialisation(path + "index.xml");
                this.currentId = this.index.size();
            } catch (Exception e) {
                this.index = new HashMap<Integer, String>();
            }
        } else {
            this.currentId = 0;
            this.index = new HashMap<Integer, String>();
        }

        this.fopFactory = FopFactory.newInstance();
    }

    public static GestionDocuments getInstance() {
        if (instance == null) {
            instance = new GestionDocuments();
        }
        return instance;
    }

    public void destruction() {
        GestionXml xml = new GestionXml();
        try {
            xml.serialisation(this.path + "index.xml", this.index);
        } catch (Exception e) {
        }
    }

    //TODO : Verifier la validité du document, verifier qu'il n'y a pas de doublons
    public void depotDocument(byte[] doc, String fileName) throws IOException {
        File file = new File(this.path + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(doc);
        fos.close();
        index.put(this.currentId, fileName);
        this.currentId++;
        System.out.println(this.index.toString());
    }

    public Map<Integer, String> rechercheDocument(List<String> motsCles) throws Exception {
        GestionXml xml = new GestionXml();
        Map<Integer, String> results = new HashMap<Integer, String>();
        for (Entry<Integer, String> entry : this.index.entrySet()) {
            String nomFichier = this.path + entry.getValue();
            String result = xml.rechercherMotsCle(nomFichier, motsCles);
            if (!result.equals("null")) {
                results.put(entry.getKey(), result);
            }
        }
        return results;
    }

    public Document retourneDocument(int id) throws IOException {
        byte[] content;
        String fileName = this.index.get(id);
        File file = new File(this.path + fileName);
        FileInputStream fis = new FileInputStream(file);
        content = new byte[(int) file.length()];
        fis.read(content);
        fileName = "Fichier introuvable";
        content = new byte[2];
        Document result = new Document(fileName, content);
        return result;
    }

    public Document genererPDF(byte[] fopFile, int id) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();

            Source src = new StreamSource(new ByteArrayInputStream(fopFile));
            Result res = new SAXResult(fop.getDefaultHandler());
            transformer.transform(src, res);
            out.flush();
        } catch (Exception e) {
        }
        Document result = new Document(this.index.get(id), out.toByteArray());
        return result;
    }
}
